//
//  SISSProgressViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/3/13.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSProgressViewController.h"
#import "SISSComboBoxViewProgress.h"
#import "SISSComboBoxView.h"
#import "SISSHouseProgressManageCell.h"
#import "SISSPassengerProgressManageViewController.h"
#import "SISSRentOutProgressManageViewController.h"
#import "SISSTenantProgressManageViewController.h"
#import "SISSHouseCooperationProgressManageViewController.h"
#import "SISSPassengerCooperationProgressManageViewController.h"
#import "SISSJsonRequestNetworkingManager+Progress.h"
#import "SISSHouseProgressViewController.h"

#import "SISSChannelLabel.h"

static NSString *houseProgressManageCellReuseID = @"houseProgressManageCellReuseID";
@interface SISSProgressViewController ()<SISSComboBoxViewProgressDelegate,UITableViewDataSource,UITableViewDelegate>

// 频道标签滚动视图
@property (weak, nonatomic) UIScrollView *channelScrollView;
/** 筛选视图 */
@property (weak, nonatomic) SISSComboBoxViewProgress *filterView;
/** tableView */
@property (weak, nonatomic) SISSBaseTableView *tableView;
/** 客源进度管理控制器 */
@property (weak, nonatomic) SISSPassengerProgressManageViewController *passengerProgressManageVC;
/** 出租进度管理控制器 */
@property (weak, nonatomic) SISSRentOutProgressManageViewController *rentOutProgressManageVC;
/** 租客进度管理控制器 */
@property (weak, nonatomic) SISSTenantProgressManageViewController *tenantProgressManageVC;
/** 房源合作进度管理控制器 */
@property (weak, nonatomic) SISSHouseCooperationProgressManageViewController *houseCooperationProgressManageVC;
/** 客源合作进度管理控制器 */
@property (weak, nonatomic) SISSPassengerCooperationProgressManageViewController *passengerCooperationProgressManageVC;

/* 房源进度管理模型数组 */
@property (strong, nonatomic) NSArray<SISSHouseProgressModel *> *houseProgressArr;

/** 区域 */
@property (copy, nonatomic) NSString *region;
/** 街道办 */
@property (copy, nonatomic) NSString *regionDetail;
/** 价格 */
@property (copy, nonatomic) NSString *price;
/** 户型 */
@property (copy, nonatomic) NSString *houseType;
/** 面积 */
@property (copy, nonatomic) NSArray *area;
/** 朝向 */
@property (copy, nonatomic) NSArray *direction;
/** 装修程度 */
@property (copy, nonatomic) NSArray *decoration;
/** 委托方式 */
@property (copy, nonatomic) NSArray *entrustWay;
/** 委托次数 */
@property (copy, nonatomic) NSArray *entrustCount;
/** 进度 */
@property (copy, nonatomic) NSArray *entrustProgress;

/* 频道标签模型数组 */
@property (strong, nonatomic) NSArray *channels;
/* 频道标签数组 */
@property (strong, nonatomic) NSMutableArray *labelsM;
///
@property (assign, nonatomic) NSInteger selectedIndex;

@end

@implementation SISSProgressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 添加segmentControl
//    UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWithItems:@[@"房源", @"客源", @"房源合作", @"客源合作"]];
//    segmentControl.selectedSegmentIndex = 0;
//    segmentControl.tintColor = COLOR(0x249DC5);
//    [segmentControl addTarget:self action:@selector(segmentControlbutClick:) forControlEvents:UIControlEventValueChanged];
//    self.navigationItem.titleView = segmentControl;
    
    
//    [self requestHouseProgressManageData];
    
    WeakSelf
    [kSISSRefresh prepareHeaderRefresh:self.tableView loadDataBlock:^{
        kSISSRefresh.refreshType = SISSRefressTypeUpDown;
        [weakSelf upDownLoadData];
    }];
    
    
    //    [kSISSRefresh prepareFooterRefresh:self.tableView reloadDataBlock:^{
    //        kSISSRefresh.refreshType = SISSRefressTypeReloadMore;
    //        [weakSelf reloadMoreData];
    //    }];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.selectedIndex == 0) {
        [self requestHouseProgressManageData];
    } else if (self.selectedIndex == 1) {
        [self.passengerProgressManageVC requestPassengerProgressManageData];
    } else if (self.selectedIndex == 2){
        [self.rentOutProgressManageVC requestRentOutProgressManageData];
    } else if (self.selectedIndex == 3){
        [self.tenantProgressManageVC requestTenantProgressManageData];
    } else if (self.selectedIndex == 4){
        [self.houseCooperationProgressManageVC requestHouseCooperationProgressManageData];
    } else if (self.selectedIndex == 5) {
        [self.passengerCooperationProgressManageVC requestPassengerCooperationProgressManageData];
    }
    
}

#pragma mark - SISSComboBoxViewDelegate
- (void)comboBoxViewDidSelectDisplayTypeNormalWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title {
    
    if ([rootItemTitle isEqualToString:@"售价"]) {
        self.price = title;
    } else if ([rootItemTitle isEqualToString:@"户型"]) {
        self.houseType = title;
    }
    [self requestHouseProgressManageData];
}

- (void)comboBoxViewDidSelectDisplayTypeMultilayerWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title subtitle:(NSString *)subtitle {
    
    self.region = title;
    self.regionDetail = subtitle;
    [self requestHouseProgressManageData];
}

- (void)comboBoxViewDidSelectDisplayTypeFiltersWithTitle:(NSString *)title subtitles:(NSArray *)subtitles {

    if ([title isEqualToString:@"委托方式"]) {
        self.entrustWay = @[];
        self.entrustWay = subtitles;
    } else if ([title isEqualToString:@"委托次数"]) {
        self.entrustCount = @[];
        self.entrustCount = subtitles;
    } else if ([title isEqualToString:@"进度"]) {
        self.entrustProgress = @[];
        self.entrustProgress = subtitles;
    } else if ([title isEqualToString:@"面积"]) {
        self.area = @[];
        self.area = subtitles;
    } else if ([title isEqualToString:@"朝向"]) {
        self.direction = @[];
        self.direction = subtitles;
    } else if ([title isEqualToString:@"装修程度"]) {
        self.decoration = @[];
        self.decoration = subtitles;
    }
}

- (void)comboBoxViewDisplayTypeFiltersConfirmClickAction {
    
    [self requestHouseProgressManageData];
    
    self.entrustWay = @[];
    self.entrustCount = @[];
    self.entrustProgress = @[];
    self.area = @[];
    self.direction = @[];
    self.decoration = @[];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    [tableView tableViewDisplayWithMessage:@"暂无数据" ifNecessaryForRowCount:self.houseProgressArr.count];
//    return 2;
    return self.houseProgressArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    SISSHouseProgressManageCell *cell = [tableView dequeueReusableCellWithIdentifier:houseProgressManageCellReuseID forIndexPath:indexPath];
    cell.houseProgressModel = self.houseProgressArr[indexPath.row];
    
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SISSHouseProgressViewController *vc = [[SISSHouseProgressViewController alloc] init];
    vc.deleteCompletedBlock = ^{
        
        [self requestHouseProgressManageData];
    };
    vc.title = @"房源进度";
    vc.houseProgressModel = self.houseProgressArr[indexPath.row];
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark-创建频道标签的主方法
- (void)createChannelLabels {
    // 获取频道标签数组
    self.channels = @[@"房源", @"客源", @"出租", @"求租", @"房源合作", @"客源合作"];
    
    CGFloat labelW = 80;
    CGFloat labelH = 44;
//    CGFloat labelX = 10;
    // 遍历频道标签模型数组,循环的创建label
    for (NSInteger i = 0; i < self.channels.count; i++) {
        // 创建频道标签控制
        SISSChannelLabel *label = [[SISSChannelLabel alloc] init];
        label.textColor = MAIN_TEXT_COLOR;
        // 添加到父控件
        [self.channelScrollView addSubview:label];
//        labelW = [self.channels[i] boundingRectWithSize:CGSizeMake(44, 16) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}  context:nil].size.width;
        // 设置frame
        CGFloat labelX = labelW * i;
        label.frame = CGRectMake(labelX, 0, labelW, labelH);
        // 赋值
        label.text = self.channels[i];
        
        // 给每创建的一个label添加点击事件
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(channelLabelTapClick:)];
        [label addGestureRecognizer:tap];
        // 开启交互
        label.userInteractionEnabled = YES;
        // 给label添加tag值,方便点击时获取点击的label的索引
        label.tag = i;
        
        // 每创建一个label,就向数组里面添加一个
        [self.labelsM addObject:label];
        
        // 把第0个label(头条)设置为最大的缩放比
        if (i == 0) {
            label.scale = 1.0;
        }
    }
    
    // 设置channelScrollView的滚动范围
    self.channelScrollView.contentSize = CGSizeMake(labelW * self.channels.count, 0);
}

#pragma mark-实现手势点击事件
- (void)channelLabelTapClick:(UITapGestureRecognizer *)tap {
    // 1.把选中的label居中
    // 获取选中的label
    SISSChannelLabel *tapLabel = (SISSChannelLabel *)tap.view;
    // 计算tapLabel滚动到居中时,需要的距离
    CGFloat offsetX = tapLabel.center.x - self.view.bounds.size.width * 0.5;
    
    // 设定最大和最小滚动范围
    CGFloat minOffsetX = 0;
    CGFloat maxOffsetX = self.channelScrollView.contentSize.width - self.view.bounds.size.width + 44;
    if (offsetX < minOffsetX) {
        offsetX = minOffsetX;
    }
    if (offsetX > maxOffsetX) {
        offsetX = maxOffsetX;
    }
    // label居中时,需要滚动到的点
    CGPoint point = CGPointMake(offsetX, 0);
    // 选中label居中时需要执行的方法
    [self.channelScrollView setContentOffset:point animated:YES];
    
    // 2.把label对应的新闻视图滚动到对应的位置 : 滚动到指定的位置
    //    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:tapLabel.tag inSection:0];
    //    [self.homeCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    [self channelItemClickWithIndex:tapLabel.tag];
    // 遍历所有的标签,只把选中的标签拿出来,赋值为最大的缩放比,其他的全部赋值最小的缩放比
    for (NSInteger i = 0; i < self.labelsM.count; i++) {
        
        // 循环的一个一个的取标签
        SISSChannelLabel *label = self.labelsM[i];
        
        // 判断取出的标签,是否是选中的标签
        if (i == tapLabel.tag) {
            label.scale = 1.0;
        } else {
            label.scale = 0.0;
        }
    }
}



#pragma mark - navigationItem
- (void)setupNavigationItems {
    
    self.labelsM = [NSMutableArray array];
    UIScrollView *channelScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    channelScrollView.showsHorizontalScrollIndicator = NO;
    channelScrollView.showsVerticalScrollIndicator = NO;
    self.channelScrollView = channelScrollView;
    self.navigationItem.titleView = channelScrollView;
    
    [self createChannelLabels];
}

#pragma mark - UI
- (void)setupSubviews {
    [super setupSubviews];
    
    SISSComboBoxViewProgress *filterView = [[SISSComboBoxViewProgress alloc] initWithFrame:CGRectMake(0, NAVIGATION_HEIGHT, SCREEN_WIDTH, 44) isHouseResource:YES];
    filterView.delegate = self;
    [self.view addSubview:filterView];
    self.filterView = filterView;
    NSLog(@"%f",NAVIGATION_HEIGHT);
    SISSBaseTableView *tableView = [[SISSBaseTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    // 自动行高
    tableView.estimatedRowHeight = 107;
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [tableView registerNib:[UINib nibWithNibName:@"SISSHouseProgressManageCell" bundle:nil] forCellReuseIdentifier:houseProgressManageCellReuseID];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(filterView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-kTabBarHeight);
    }];
    
    // 添加客源进度管理视图
    SISSPassengerProgressManageViewController *passengerProgressManageVC = [[SISSPassengerProgressManageViewController alloc] init];
    passengerProgressManageVC.navigationHeight = NAVIGATION_HEIGHT;
    [self.view addSubview:passengerProgressManageVC.view];
    [self addChildViewController:passengerProgressManageVC];
    //    passengerCooperationVC.view.frame = CGRectOffset(self.view.frame, 0, 64);
    [passengerProgressManageVC didMoveToParentViewController:self];
    [passengerProgressManageVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.passengerProgressManageVC = passengerProgressManageVC;
    self.passengerProgressManageVC.view.hidden = YES;
    
    // 添加出租进度管理视图
    SISSRentOutProgressManageViewController *rentOutProgressManageVC = [[SISSRentOutProgressManageViewController alloc] init];
    rentOutProgressManageVC.navigationHeight = NAVIGATION_HEIGHT;
    [self.view addSubview:rentOutProgressManageVC.view];
    [self addChildViewController:rentOutProgressManageVC];
    //    passengerCooperationVC.view.frame = CGRectOffset(self.view.frame, 0, 64);
    [rentOutProgressManageVC didMoveToParentViewController:self];
    [rentOutProgressManageVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.rentOutProgressManageVC = rentOutProgressManageVC;
    self.rentOutProgressManageVC.view.hidden = YES;
    
    // 添加租客进度管理视图
    SISSTenantProgressManageViewController *tenantProgressManageVC = [[SISSTenantProgressManageViewController alloc] init];
    tenantProgressManageVC.navigationHeight = NAVIGATION_HEIGHT;
    [self.view addSubview:tenantProgressManageVC.view];
    [self addChildViewController:tenantProgressManageVC];
    //    passengerCooperationVC.view.frame = CGRectOffset(self.view.frame, 0, 64);
    [tenantProgressManageVC didMoveToParentViewController:self];
    [tenantProgressManageVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.tenantProgressManageVC = tenantProgressManageVC;
    self.tenantProgressManageVC.view.hidden = YES;
    
    // 添加房源合作进度管理视图
    SISSHouseCooperationProgressManageViewController *houseCooperationProgressManageVC = [[SISSHouseCooperationProgressManageViewController alloc] init];
    houseCooperationProgressManageVC.navigationHeight = NAVIGATION_HEIGHT;
    [self.view addSubview:houseCooperationProgressManageVC.view];
    [self addChildViewController:houseCooperationProgressManageVC];
    //    passengerCooperationVC.view.frame = CGRectOffset(self.view.frame, 0, 64);
    [houseCooperationProgressManageVC didMoveToParentViewController:self];
    [houseCooperationProgressManageVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.houseCooperationProgressManageVC = houseCooperationProgressManageVC;
    self.houseCooperationProgressManageVC.view.hidden = YES;
    
    // 添加客源合作进度管理视图
    SISSPassengerCooperationProgressManageViewController *passengerCooperationProgressManageVC = [[SISSPassengerCooperationProgressManageViewController alloc] init];
    passengerCooperationProgressManageVC.navigationHeight = NAVIGATION_HEIGHT;
    [self.view addSubview:passengerCooperationProgressManageVC.view];
    [self addChildViewController:passengerCooperationProgressManageVC];
    //    passengerCooperationVC.view.frame = CGRectOffset(self.view.frame, 0, 64);
    [passengerCooperationProgressManageVC didMoveToParentViewController:self];
    [passengerCooperationProgressManageVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.passengerCooperationProgressManageVC = passengerCooperationProgressManageVC;
    self.passengerCooperationProgressManageVC.view.hidden = YES;
}


- (void)segmentControlbutClick:(UISegmentedControl *)sender {
    
    if (sender.selectedSegmentIndex != 0) {
        [self.filterView.comBoBoxView dismissPopView];
    }
    if (sender.selectedSegmentIndex != 1) {
        [self.passengerProgressManageVC.filterView.comBoBoxView dismissPopView];
    }
    if (sender.selectedSegmentIndex != 2) {
        [self.houseCooperationProgressManageVC.filterView.comBoBoxView dismissPopView];
    }
    if (sender.selectedSegmentIndex != 3) {
        [self.passengerCooperationProgressManageVC.filterView.comBoBoxView dismissPopView];
    }
    self.passengerProgressManageVC.view.hidden = sender.selectedSegmentIndex != 1;
    self.houseCooperationProgressManageVC.view.hidden = sender.selectedSegmentIndex != 2;
    self.passengerCooperationProgressManageVC.view.hidden = sender.selectedSegmentIndex != 3;
    
    if (sender.selectedSegmentIndex == 0) {
        [self requestHouseProgressManageData];
    } else if (sender.selectedSegmentIndex == 1) {
        [self.passengerProgressManageVC requestPassengerProgressManageData];
    } else if (sender.selectedSegmentIndex == 2){
        [self.houseCooperationProgressManageVC requestHouseCooperationProgressManageData];
    } else if (sender.selectedSegmentIndex == 2) {
        [self.passengerCooperationProgressManageVC requestPassengerCooperationProgressManageData];
    }
}

- (void)channelItemClickWithIndex:(NSInteger)index {
    self.selectedIndex = index;
    if (index != 0) {
        [self.filterView.comBoBoxView dismissPopView];
    }
    if (index != 1) {
        [self.passengerProgressManageVC.filterView.comBoBoxView dismissPopView];
    }
    if (index != 2) {
        [self.rentOutProgressManageVC.filterView.comBoBoxView dismissPopView];
    }
    if (index != 3) {
        [self.tenantProgressManageVC.filterView.comBoBoxView dismissPopView];
    }
    if (index != 4) {
        [self.houseCooperationProgressManageVC.filterView.comBoBoxView dismissPopView];
    }
    if (index != 5) {
        [self.passengerCooperationProgressManageVC.filterView.comBoBoxView dismissPopView];
    }
    
    self.passengerProgressManageVC.view.hidden = index != 1;
    self.rentOutProgressManageVC.view.hidden = index != 2;
    self.tenantProgressManageVC.view.hidden = index != 3;
    self.houseCooperationProgressManageVC.view.hidden = index != 4;
    self.passengerCooperationProgressManageVC.view.hidden = index != 5;
    
    if (index == 0) {
        [self requestHouseProgressManageData];
    } else if (index == 1) {
        [self.passengerProgressManageVC requestPassengerProgressManageData];
    } else if (index == 2){
        [self.rentOutProgressManageVC requestRentOutProgressManageData];
    } else if (index == 3){
        [self.tenantProgressManageVC requestTenantProgressManageData];
    } else if (index == 4){
        [self.houseCooperationProgressManageVC requestHouseCooperationProgressManageData];
    } else if (index == 5) {
        [self.passengerCooperationProgressManageVC requestPassengerCooperationProgressManageData];
    }
}

#pragma mark - 上下拉刷新加载方法
- (void)upDownLoadData {
    
//    self.pageNo = 1;
    
    [self requestHouseProgressManageData];
    
}

- (void)reloadMoreData {
    
//    self.pageNo += 1;
    
    [self requestHouseProgressManageData];
}

#pragma mark - 加载数据
- (void)requestHouseProgressManageData {
    
    NSString *region = self.region ? self.region : @"不限";
    NSString *regionDetail = self.regionDetail ? self.regionDetail : @"不限";
    NSString *price = self.price ? self.price : @"";
    NSString *houseType = self.houseType ? self.houseType : @"不限";
    
    NSDictionary *parameters = @{
                                 @"spId":[SISSUserAccount shared].spId,
                                 @"region":region,
                                 @"regionDetail":regionDetail,
                                 @"price":price,
                                 @"houseType":houseType,
                                 @"area":self.area,
                                 @"direction":self.direction,
                                 @"decoration":self.decoration,
                                 @"entrustWay":self.entrustWay,
                                 @"entrustCount":self.entrustCount,
                                 @"entrustProgress":self.entrustProgress
                                 };
    
    WeakSelf
    [kJsonRequestNetworkingManager requestFilterHouseProgressWithParameters:parameters success:^(NSArray<SISSHouseProgressModel *> *houseArr) {
        
        weakSelf.houseProgressArr = houseArr;
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            [weakSelf.tableView reloadData];
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
        }];
        
    } failed:^(NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        NSLog(@"%@",error);
    }];
}

#pragma mark - 懒加载

- (NSArray *)area {
    if (_area == nil) {
        _area = [NSArray array];
    }
    return _area;
}

- (NSArray *)direction {
    if (_direction == nil) {
        _direction = [NSArray array];
    }
    return _direction;
}

- (NSArray *)decoration {
    if (_decoration == nil) {
        _decoration = [NSArray array];
    }
    return _decoration;
}

- (NSArray *)entrustWay {
    if (!_entrustWay) {
        _entrustWay = [NSArray array];
    }
    return _entrustWay;
}

- (NSArray *)entrustCount {
    if (!_entrustCount) {
        _entrustCount = [NSArray array];
    }
    return _entrustCount;
}

- (NSArray *)entrustProgress {
    if (!_entrustProgress) {
        _entrustProgress = [NSArray array];
    }
    return _entrustProgress;
}

@end
